package com.tarena.baking.security;


import com.tarena.baking.mapper.UserMapper;
import com.tarena.baking.pojo.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserLoginVO user = mapper.selectByUserName(s);

        if (user != null) {
            String role = user.getIsAdmin() == 0 ? "USER" : "ADMIN";
            List<GrantedAuthority> authorities =
                    AuthorityUtils.createAuthorityList(role);

            AuthenticationUser authenticationUser = new AuthenticationUser(
                    user.getId(),
                    user.getUserName(),
                    user.getPassword(),
                    true,
                    authorities);
            return authenticationUser;
        }
        return null;
    }

}
